<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="form" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="门诊名称">
              <el-input
                v-model="listQuery.name"
                placeholder="门诊名称"
                style="width: 200px;"
                class="filter-item"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话">
              <el-input
                v-model="listQuery.tel"
                placeholder="联系电话"
                style="width: 200px;"
                class="filter-item"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getList">查询</el-button>
        <el-button
          type="primary"
          icon="el-icon-plus"
          class="filter-item"
          @click="addClinic"
          v-if="hasPermission('sys:clinic:add')"
        >
          <span>新增门诊</span>
        </el-button>
      </el-form>
    </div>
    <div>
      <h3>门诊管理#</h3>
    </div>

    <!--功能点授权-->
    <el-dialog
      :title="title"
      class="dialogAdd"
      :visible.sync="dialogAddgsVisible"
      :width="width"
      top="30px"
    >
      <template>
        <el-input
          v-model="permListQuery.title"
          placeholder="菜单名称"
          style="width: 200px;"
          class="filter-item"
        />
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getPermList">查询</el-button>
      </template>

      <template>
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="setPerm">授权</el-button>
      </template>

      <tree-table
        :height="tableHeight"
        :data="permList"
        :columns="columns"
        :root_value="'0'"
        :primary_fld="'id'"
        :expand-all="expandAll"
        :parent_fld="'parentId'"
        :select_fld="'false'"
        ref="treeTable"
      >
        <el-table-column label="类别" min-width="75" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.icon? "菜单权限":"功能权限"}}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" min-width="75" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.granted? "已授权":"未授权"}}</span>
          </template>
        </el-table-column>
      </tree-table>
    </el-dialog>

    <!--门诊列表-->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="门诊logo" prop="logo" align="center" width="150">
        <template slot-scope="{row}">
          <img v-if="row.logo" :src="row.logo" alt="门诊logo" style="max-width: 100px" />
        </template>
      </el-table-column>

      <el-table-column label="门诊名称" prop="name" align="center">
        <template slot-scope="{row}">
          <span>{{row.name}}</span>
        </template>
      </el-table-column>

      <el-table-column label="门诊地址" prop="addr" align="center">
        <template slot-scope="{row}">
          <span>{{row.addr}}</span>
        </template>
      </el-table-column>

      <el-table-column label="门诊电话" prop="tel" align="center">
        <template slot-scope="{row}">
          <span>{{row.tel}}</span>
        </template>
      </el-table-column>

      <el-table-column label="门诊简介" prop="introduce" align="center">
        <template slot-scope="{row}">
          <span>{{row.introduce}}</span>
        </template>
      </el-table-column>

      <el-table-column label="营业范围" prop="business" align="center">
        <template slot-scope="{row}">
          <span>{{row.business}}</span>
        </template>
      </el-table-column>

      <el-table-column label="到期时间" prop="expireDate" align="center" width="160">
        <template slot-scope="{row}">
          <span>{{row.expireDate | timeFormat}}</span>
        </template>
      </el-table-column>

      <el-table-column label="启用" prop="isExpired" align="center">
        <template slot-scope="{row}">
          <span>{{row.isExpired | expired}}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" prop="id" align="center" width="180">
        <template slot-scope="{row}">
          <!--          <el-button type="primary" size="mini" @click="DeptDelete">删除</el-button>-->
          <el-button type="primary" size="mini" @click="menuPermissions(row.id)">菜单授权</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="clinicTitle"
      class="dialogAdd"
      :visible.sync="dialogAddClinicVisible"
      :width="width"
      top="30px"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="门诊logo">
          <el-upload
            ref="upload"
            class="avatar-uploader"
            :action="action"
            :disabled="!hasPermission('perm')"
            :drag="true"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.logo" :src="form.logo" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>

        <el-form-item label="门诊名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>

        <el-form-item label="门诊地址" prop="addr">
          <el-input v-model="form.addr" />
        </el-form-item>

        <el-form-item label="门诊电话" prop="tel">
          <el-input v-model="form.tel" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>

        <el-form-item label="官网" prop="website">
          <el-input v-model="form.website" />
        </el-form-item>

        <el-form-item label="门诊简介">
          <el-input v-model="form.introduce" type="textarea" />
        </el-form-item>

        <el-form-item label="业务范围">
          <el-input v-model="form.business" type="textarea" />
        </el-form-item>

        <el-form-item label="到期时间" prop="expireDate">
          <el-date-picker
            type="datetime"
            v-model="form.expireDate"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            :style="{width: '100%'}"
            placeholder="请选择时间选择时间选择"
            clearable
          ></el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="saveClinic('form')">提交</el-button>
          <el-button @click="resetForm('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  searchClinic,
  grantClinic,
  grantClinicPerm,
  eidtClinic,
  addClinic
} from "@/api/clinic";
import {
  validateTelephone,
  validatePhoneNumber,
  validEmail,
  validateUrl
} from "@/utils/validate";
import Pagination from "@/components/Pagination";
import treeTable from "@/components/treeTable/permTree";

export default {
  name: "clinicPerm",
  components: { Pagination, treeTable },
  data() {
    const isNUll = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("不能为空"));
      } else {
        callback();
      }
    };
    const checkTel = (rule, value, callback) => {
      if (!validateTelephone(value) && !validatePhoneNumber(value)) {
        return callback(new Error("门诊电话格式不正确"));
      } else {
        callback();
      }
    };
    const checkMail = (rule, value, callback) => {
      if (value) {
        if (!validEmail(value)) {
          callback(new Error("邮箱格式不正确"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    const checkWebsite = (rule, value, callback) => {
      if (value) {
        if (!validateUrl(value)) {
          callback(new Error("网址格式不正确"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      clinicTitle: "",
      dialogAddClinicVisible: false,
      action: "",
      form: {
        logo: "",
        name: "元康互联网科技有限公司",
        addr: "",
        tel: "",
        introduce: "",
        business: "",
        pic: [],
        email: "",
        website: "",
        expireDate: "",
        version: 0
      },
      rules: {
        name: [
          { required: true, message: "请输入门诊名称", trigger: "blur" },
          { min: 2, max: 32, message: "长度在 2 到 32 个字符", trigger: "blur" }
        ],
        addr: [
          { required: true, message: "请输入门诊地址", trigger: "blur" },
          { min: 2, max: 32, message: "长度在 2 到 32 个字符", trigger: "blur" }
        ],
        expireDate: [
          { required: true, message: "请选择到期时间", trigger: "blur" }
        ],
        tel: [
          {
            validator: isNUll,
            required: true,
            message: "请输入门诊电话",
            trigger: "blur"
          },
          {
            validator: checkTel,
            required: true,
            message: "门诊电话有误",
            trigger: "change"
          }
        ],
        email: [
          {
            validator: checkMail,
            required: false,
            message: "邮箱格式有误",
            trigger: "change"
          }
        ],
        website: [
          {
            validator: checkWebsite,
            required: false,
            message: "网址格式有误",
            trigger: "change"
          }
        ]
      },

      width: "800px",
      tableKey: 0,
      listLoading: true,
      list: null,
      driver: null,
      listData: null,
      total: 0,
      listQuery: {
        page: 1,
        pageSize: 10
      },

      RoleInfo: {},

      permList: [],
      permListQuery: {},

      addForm: {
        name: "",
        creditCode: "",
        address: "",
        tel: "",
        id: ""
      },
      dialogAddgsVisible: false,
      title: "",

      tableHeight: 500,
      expandAll: true,
      columns: [{ value: "permission", text: "菜单", minWidth: "300" }]
    };
  },
  filters: {
    expired(s) {
      let status = { "1": "到期用户", "0": "正常用户", "-1": "永久用户" };
      return status[s];
    },
    timeFormat(t) {
      return new Date(t).Format("yyyy-MM-dd hh:mm:ss");
    },
    checkStatus: function(s) {
      return s === 1 ? "授权" : "未授权";
    }
  },
  created() {
    window.app = this;
    this.action = process.env.VUE_APP_BASE_API + "/file/upload";
    this.getList();
  },
  mounted: function() {
    // 监听窗口大小变化
    let self = this;
    self.width = window.innerWidth * 0.8 + "px";
  },
  methods: {
    addClinic() {
      this.dialogAddClinicVisible = true;
      this.form = {
        imageUrl: "",
        logo: "",
        name: "",
        addr: "",
        tel: "",
        introduce: "",
        business: "",
        pic: [],
        email: "",
        website: "",
        version: 0
      };
    },
    saveClinic(formName) {
      const _that = this;
      this.$refs[formName].validate(valid => {
        if (valid) {
          const data = _that.form;
          data.pic = "";
          console.log(_that.form);

          if (data.id) {
            eidtClinic(data).then(response => {
              if (response.code === 200) {
                this.$message({
                  showClose: true,
                  message: "编辑门诊信息成功",
                  type: "success"
                });
                this.form = response.data;
                this.dialogAddClinicVisible = false;
                this.getList()
              }
            });
          } else {
            addClinic(data).then(response => {
              if (response.code === 200) {
                this.$message({
                  showClose: true,
                  message: "新增门诊信息成功",
                  type: "success"
                });
                // this.form = response.data;
                this.dialogAddClinicVisible = false;
                this.getList()
              }
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleAvatarSuccess(res, f) {
      // this.form.imageUrl = URL.createObjectURL(f.raw)
      this.form.imageUrl = res.file;
      this.form.logo = res.file;
    },
    beforeAvatarUpload(file) {
      // 关键点注入用户凭证
      this.$refs.upload.headers.Authorization = this.$store.getters.token;
      console.log(this.$refs.upload.headers);
      const isJPG = file.type === "image/jpeg";
      const isPng = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPng) {
        this.$message.error("上传头像图片只能是 JPG 或 png 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return (isJPG || isPng) && isLt2M;
    },
    setPerm() {
      let dataSet = {
        id: this.permListQuery.clinicId,
        idx: []
      };
      this.permList.map(item => {
        if (item["false"]) {
          dataSet.idx.push(item.id);
        }
      });
      grantClinicPerm(dataSet).then(data => {
        if (data.code === 200) {
          //授权成功
          this.$message("授权成功");
          this.dialogAddgsVisible = false;
        }
      });
    },

    addDept() {
      {
        this.dialogAddgsVisible = true;
        this.title = "新增角色";
      }
    },
    getList() {
      this.listLoading = true;
      searchClinic(this.listQuery).then(response => {
        this.list = response.data.list;
        this.total = response.data.totalCount;
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false;
        }, 0.5 * 1000);
      });
    },
    menuPermissions(id) {
      this.dialogAddgsVisible = true;
      this.title = "菜单授权";
      this.permListQuery.clinicId = id;
      this.getPermList();
    },
    getPermList() {
      grantClinic(this.permListQuery).then(response => {
        this.permList = response.page;
        this.permList.map(row => {
          row.id = row.id + "";
          row.parentId = row.parentId + "";
          if (row.granted) {
            this.$refs.treeTable.chooseNode(row);
          }
        });

        setTimeout(() => {
          this.listLoading = false;
        }, 0.5 * 1000);
      });
    }
  }
};
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}

.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
